package com.zjitc.controller.admin;

import com.github.pagehelper.PageInfo;
import com.zjitc.model.Category;
import com.zjitc.model.Product;
import com.zjitc.service.CategoryService;
import com.zjitc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/10 0010
 * @description:
 */
@Controller
@RequestMapping(value = "/admin/product")
public class AdminProductControl {

    @Autowired
    private ProductService service;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping(value = "/findProducts")
    @ResponseBody
    public ModelAndView findProducts(
            @RequestParam(name = "pageNum", defaultValue = "1", required = false) int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "4", required = false) int pageSize) {
        ModelAndView mv = new ModelAndView(new InternalResourceView("/admin/product/list.jsp"));
        List<Product> products = service.findProducts(pageNum, pageSize);
        PageInfo info = new PageInfo(products);
        mv.addObject("page", info);
        return mv;
    }

    @RequestMapping(value = "/findAllCategories")
    public ModelAndView findAllCategories() {
        List<Category> categories = categoryService.findAll();
        ModelAndView mv = new ModelAndView(new InternalResourceView("/admin/product/add.jsp"));
        mv.addObject("categories", categories);
        return mv;
    }

    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public ModelAndView addProduct(@ModelAttribute Product product, HttpServletRequest request,
                                   @RequestParam("file") MultipartFile file) throws IOException {
        uploadProduct(product, request, file);
        service.add(product);
        ModelAndView mv = new ModelAndView(new InternalResourceView("/admin/product/add.jsp"));
        return mv;
    }

    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    public String updateProduct(@ModelAttribute Product product, HttpServletRequest request,
                                @RequestParam("file") MultipartFile file) throws IOException {
        /**
         * 也可以用MD5校验解决文件是否为同一个文件。放在服务器吧，先不判定
         */
        System.out.println(file);
        if (!file.isEmpty()) {
            uploadProduct(product, request, file);

        }

        service.update(product);
        return "redirect:/admin/product/findProducts.do";
    }

    /**
     * /** *              想删除表中的数据必须先删除product中的数据 图片上传
     */
    public void uploadProduct(Product product, HttpServletRequest request, MultipartFile file)
            throws IOException {
        //如果文件不为空，写入上传路径
        if (!file.isEmpty()) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("/images/upload/");
            //上传文件名
            String filename = file.getOriginalFilename();
            // 获取图片的扩展名
            String extensionName = filename
                    .substring(filename.lastIndexOf(".") + 1);
            System.out.println(extensionName);
            // 新的图片文件名 = 获取时间戳+"."图片扩展名
            String newFileName = String.valueOf(System.currentTimeMillis())
                    + "." + extensionName;
            File filepath = new File(path, newFileName);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + newFileName));
            //获取服务器名称
            String requestServerName = request.getServerName();
            //获取服务器端口
            int serverPort = request.getServerPort();
            product.setImage("images/upload/" + newFileName);
        }
    }

    @RequestMapping(value = "/adminDeleteByPid")
    @ResponseBody
    public String adminDeleteByPid(String pid) {
        String s = service.deleteByPid(pid);
        return s;
    }

    @RequestMapping(value = "/adminFindProductByPid")
    @ResponseBody
    public ModelAndView adminFindProductByPid(String pid) {
        Product product = service.findByPid(pid);
        List<Category> categories = categoryService.findAll();
        ModelAndView mv = new ModelAndView(new InternalResourceView("/admin/product/edit.jsp"));
        mv.addObject("product", product);
        mv.addObject("categories", categories);
        return mv;
    }
}
